package api.google.android;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.graphics.*;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.widget.Toast;

import com.google.android.maps.*;

public class GoogleMapActivity extends MapActivity {

    private String securityKey = "";
    private String groupName = "";
    private final long GPS_UPDATE_TIME_IN_MILLIS = 10000;
    private final float GPS_UPDATE_MIN_DISTANCE_IN_METERS = 1;
    MapOverlay mapOverlay;
	MapView mapView; 
    MapController mapController;
    GeoPoint p;
    LocationManager locationManager;
    LocationListener locationListener;
    ArrayList<User> myGroupMembers;
    ArrayList<GeoPoint> points;
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	} 
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
	   super.onCreate(savedInstanceState);
	   setContentView(R.layout.main);
	   
       Bundle extras = getIntent().getExtras();
       if(extras !=null) {
               groupName = extras.getString("groupName");
       }
       
       securityKey = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
       //securityKey = "14553";
       if(groupName != null && securityKey != null) {
       		myGroupMembers = getFriendsCoordinates(groupName, securityKey);
       		System.out.println("SecurityKey: " + securityKey);
       } 
       
       mapView = (MapView) findViewById(R.id.map_view);      
       mapView.setBuiltInZoomControls(true);

       locationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
       locationListener = new MyLocationListener();
       try {
    	   locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 
                   GPS_UPDATE_TIME_IN_MILLIS, 
                   GPS_UPDATE_MIN_DISTANCE_IN_METERS, 
                   locationListener);  
    	   System.out.println("DEBUG Setting locationListener SUCCEEDED");
       } catch(Exception e) {
    	   System.out.println("DEBUG Setting locationListener FAILEDs");
       }   
   }
    
    
    class MyLocationListener implements LocationListener {
    	public void onLocationChanged(Location location) {
	        sendMyLocationToServer(location);
	        Log.d("DEBUG", "My current location: " + location.getLongitude() + " long, " + location.getLatitude() + " lat.");
	        
	        p = new GeoPoint(
    	               (int) (location.getLatitude() * 1E6), 
    	               (int) (location.getLongitude() * 1E6));
	        
	        getMyGroupLocationsOnMap();
	        mapOverlay = new MapOverlay();
	        List<Overlay> listOfOverlays = mapView.getOverlays();
	        listOfOverlays.clear();
	        listOfOverlays.add(mapOverlay); 
           
	        mapController = mapView.getController();
	        mapController.animateTo(p);
	        mapController.setZoom(2); 
	        mapView.invalidate();
    	}

		private void getMyGroupLocationsOnMap() {
			points = new ArrayList<GeoPoint>();
			for(User member : myGroupMembers) {
				GeoPoint point = new GeoPoint((int) (member.getLatitude() * 1E6), (int) (member.getLongitude() * 1E6));
				points.add(point);
			}
		}

		private void sendMyLocationToServer(Location location) {
			Connection connection = new Connection("saveCoordinates");
	        connection.addPostData("longitude", Double.toString(location.getLongitude()));
	        connection.addPostData("latitude", Double.toString(location.getLatitude()));
	        connection.addPostData("group", groupName);
	        connection.addPostData("securityKey", securityKey);
	        connection.postData();
		}

        public void onProviderDisabled(String provider) {
                Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
                
        }

        public void onProviderEnabled(String provider) {
                Toast.makeText(getApplicationContext(), "Gps Endabled", Toast.LENGTH_SHORT ).show();
                
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
                
        }

    }
    
    public ArrayList<User> getFriendsCoordinates(String groupId, String securityKey) {
    	
    	//Get group members locations
    	Connection connection = new Connection("getCoordinates");
    	connection.addPostData("group", groupId);
    	connection.addPostData("securityKey", securityKey);
    	String response = connection.postData();
    	ParseJSON jsonParser = new ParseJSON();
    	List<String> coordinates = jsonParser.JsonArrayToList(response);
    	System.out.println("DEBUG: Group member coordinates before processing: " + response);
    	
    	//Extract the group members info.
    	ArrayList<User> users = new ArrayList<User>();
    	for(String coordinate : coordinates) {
    		String[] userInfo = coordinate.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\"", "").split(",");
    		User user = new User(userInfo[0], Double.valueOf(userInfo[1]), Double.valueOf(userInfo[2]));
    		users.add(user);
    	}
    	System.out.println("DEBUG: Group member coordinates: ");
    	for(User user : users) {
    		System.out.println(user);
    	}
    	return users;
    }
    
    class MapOverlay extends com.google.android.maps.Overlay {
        @Override
        public boolean draw(Canvas canvas, MapView mapView, 
        boolean shadow, long when) 
        {
            super.draw(canvas, mapView, shadow);                   
            
            //---translate the GeoPoint created in onCreate to screen pixels---
            Point screenPts = new Point();
            mapView.getProjection().toPixels(p, screenPts);
            
            //---add the marker---
            Bitmap bmp = BitmapFactory.decodeResource(
                getResources(), R.drawable.map_marker);            
            canvas.drawBitmap(bmp, screenPts.x-15, screenPts.y-32, null);	   

            
            if(points != null) {
            	for (GeoPoint point : points) {
            		Point screenPoint = new Point();
                	mapView.getProjection().toPixels(point, screenPoint);            
                    canvas.drawBitmap(bmp, screenPoint.x-15, screenPoint.y-32, null);
                }	
            }            
            return true;
        }
    }

} 


